import { reqCartList, reqDeleteCartbyid, reqUpdateChecked } from '@/api/index'

const actions = {
    async getCartList({ commit }) {
        let result = await reqCartList();
        if (result.code == 200) {
            commit("GETCARTLIST", result.data)
        }
    },

    async deleteCartbyid({ commit }, skuid) {
        let result = await reqDeleteCartbyid(skuid);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'));
        }
    },

    deleteAllChecked({ dispatch, getters }) {
        let promiseall = [];
        getters.cartlist.cartInfoList.forEach(element => {
            let promise = element.isChecked == 1 ? dispatch("deleteCartbyid", element.skuId) : '';
            promiseall.push(promise);
        });
        return Promise.all(promiseall)
    },

    // 修改单个产品勾选框状态
    async updateSingleChecked({ commit }, { skuid, isChecked }) {
        let result = await reqUpdateChecked(skuid, isChecked);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new error('fail'))
        }
    },

    updateAllChecked({ dispatch, getters }, isChecked) {
        let promiseAll = [];
        getters.cartlist.cartInfoList.forEach(element => {
            if (element.isChecked != isChecked) {
                let promise = dispatch("updateSingleChecked", { skuid: element.skuId, isChecked });
                promiseAll.push(promise)
            }
        });
        return Promise.all(promiseAll)
    }
};

const mutations = {
    GETCARTLIST(state, data) {
        state.cartlist = data
    }
};

const state = {
    cartlist: []
};

const getters = {
    cartlist(state) {
        return state.cartlist[0] || []
    }
};

export default {
    actions, mutations, state, getters
}